﻿using FakeXiecheng.API.Datubase;
using FakeXiecheng.API.Dtos;
using FakeXiecheng.API.Helper;
using FakeXiecheng.API.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FakeXiecheng.API.Services
{
    public class TouristRouteRepository : ITouristRouteRepository
    {
        private readonly AppDbContext _context;
        private readonly IPropertyMappingService _propertyMappingService;
        public TouristRouteRepository(AppDbContext context, IPropertyMappingService propertyMappingService)
        {
            _context = context;
            _propertyMappingService = propertyMappingService;
        }

        public async Task<TouristRoute> GetTouristRouteAsync(Guid touristRouteId)
        {
            return await( _context.TouristRoutes.Include(t => t.TouristRoutePictures).FirstOrDefaultAsync(n => n.Id == touristRouteId));
        }

        public async Task<PaginationList<TouristRoute>> GetTouristRoutesAsync(
            string keyword, 
            string ratingOperator,
            int? raringVlaue,
            int pageSize,
            int pageNumber,
            string orderBy
            )
        {
            IQueryable<TouristRoute> result = _context
                .TouristRoutes
                .Include(t => t.TouristRoutePictures);
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                keyword = keyword.Trim();
                result = result.Where(t => t.Title.Contains(keyword));
            }
            if (raringVlaue >= 0)
            {
                //switch (ratingOperator)
                //{
                //    case "largerThan":
                //        result = result.Where(t => t.Rating >= raringVlaue);
                //        break;
                //    case "lessThan":
                //        result = result.Where(t => t.Rating >= raringVlaue);
                //        break;
                //    case "equalTo":
                //        result = result.Where(t => t.Rating >= raringVlaue);
                //        break;
                //}
                //以上可简化代码
                result = ratingOperator switch
                {
                    "largerThan" => result.Where(t => t.Rating >= raringVlaue),
                    "lessThan" => result.Where(t => t.Rating >= raringVlaue),
                    _ => result.Where(t => t.Rating >= raringVlaue),
                };
            }
            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                var touristRouteMappingDictionary = _propertyMappingService
                    .GetPropertyMapping<TouristRouteDto, TouristRoute>();
                result=result.ApplySort(orderBy, touristRouteMappingDictionary);
            }
                //include vs join
                return await PaginationList<TouristRoute>.CreateAsync(pageNumber, pageSize, result);
        }
        public async Task<bool> TouristRouteExistsAsync(Guid touristRouteId)
        {
            return await _context.TouristRoutes.AnyAsync(t => t.Id == touristRouteId);
        }
        //public bool TouristRoutePictureExists(int pictureId)
        //{
        //    return _context.TouristRoutepictures.Any(t => t.Id == pictureId);
        //}
        public async Task<IEnumerable<TouristRoutePicture>> GetPicturesByTouristRouteIdAsync(Guid touristRouteId)
        {
            return await  _context.TouristRoutepictures.Where(p => p.TouristRouteId == touristRouteId).ToListAsync();
        }
        public async Task<TouristRoutePicture> GetPictureAsync(int pictureId)
        {
            return await _context.TouristRoutepictures.Where(p => p.Id == pictureId).FirstOrDefaultAsync();
        }

        //批量获取旅游路线数据
        public async Task<IEnumerable<TouristRoute>> GetTouristRoutesByIDListAsync(IEnumerable<Guid> Ids)
        {
            return await _context.TouristRoutes.Where(t => Ids.Contains(t.Id)).ToListAsync();
        }
        public void AddTouristRoute(TouristRoute touristRoute)
        {
            if (touristRoute == null)
            {
                throw new ArgumentNullException(nameof(touristRoute));
            }
            _context.TouristRoutes.Add(touristRoute);
            //_context.SaveChanges();
        }
        public void AddTouristRoutePicture(Guid touristRouteId, TouristRoutePicture touristRoutePicture)
        {
            if (touristRouteId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(touristRouteId));
            }
            if (touristRoutePicture == null)
            {
                throw new ArgumentNullException(nameof(touristRoutePicture));
            }
            touristRoutePicture.TouristRouteId = touristRouteId;
            _context.TouristRoutepictures.Add(touristRoutePicture);
        }
        public void DeleteTouristRoute(TouristRoute touristRoute)
        {
            _context.TouristRoutes.Remove(touristRoute);
        }
        public void DeleteTouristRoutePicture(TouristRoutePicture picture)
        {
            _context.TouristRoutepictures.Remove(picture);
        }
        public void DeleteTouristRoutes(IEnumerable<TouristRoute> touristRoutes)
        {
            _context.TouristRoutes.RemoveRange(touristRoutes);
        }
        public async Task<ShoppingCart> GetShoppingCartByUserId(string userId)
        {
            return await _context.ShoppingCarts
                .Include(s => s.User)
                .Include(s => s.ShoppingCartItems).ThenInclude(li => li.TouristRoute)
                .Where(s => s.UserId == userId)
                .FirstOrDefaultAsync();
        }
        public async Task CreateShoppingCart(ShoppingCart shoppingCart)
        {
           await _context.ShoppingCarts.AddAsync(shoppingCart);
        }
        public async Task AddShoppingCartItem(LineItem lineItem)
        {
            //异步把LineItem数据添加到数据库
            await _context.LineItems.AddAsync(lineItem);
        }
        public async Task<LineItem> GetShoppingCartItemByItemId(int lineItemId)
        {
            //用lineItemId寻找lineItem
            return await _context.LineItems
                .Where(li => li.Id == lineItemId)
                .FirstOrDefaultAsync();//FirstOrDefaultAsync用于查询获取单项数据
        }
        public async void DeleteShoppingCartItem(LineItem lineItem)
        {
            _context.LineItems.Remove(lineItem);//Remove用于删除一条数据
        }
        public async Task<IEnumerable<LineItem>> GeshoppingCartsByIdListAsync(IEnumerable<int> ids)
        {
            return await _context.LineItems.Where(li => ids.Contains(li.Id)).ToListAsync();//ToListAsync用于查询获取多项数据
        }
        public void DeleteShoppingCartItems(IEnumerable<LineItem> lineItems)
        {
            _context.LineItems.RemoveRange(lineItems);//RemoveRange用于删除数组数据
        }
        public async Task AddOrderAsync(Order order)
        {
            await _context.Orders.AddAsync(order);
        }
        public async Task<PaginationList<Order>> GetOrdersByUserId(string userId,
            int pageSize,int pageNumber)
        {
            //return  await _context.Orders.Where(li => li.UserId == userId).ToListAsync();//ToListAsync用于查询获取多项数据
            IQueryable<Order> result = _context.Orders.Where(o => o.UserId == userId);
          return   await PaginationList<Order>.CreateAsync(pageNumber, pageSize, result);
        }
        public async Task<Order> GetOrderById(Guid orderId)
        {
            return await _context.Orders
                .Include(o => o.OrderItems).ThenInclude(io => io.TouristRoute)
                .Where(o => o.Id == orderId)
                .FirstOrDefaultAsync();
        }
        public async Task<bool> SaveAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}
